var columnName;
var tableName;
var docid;
var sequenceA;
var doctemp;

var handleType;
var taohong;
var headerModel;
var footModel;
var mtDocument;
var stamp;
var username;

/**
 * 打开word文档
 */
function open_word() {

	var args = window.dialogArguments;

	doctemp = args[0];

	sequenceA = args[2]

	docid = args[1];

	columnName = args[3];

	tableName = args[4];

	handleType = args[5];

	taohong = args[6];

	headerModel = args[7];

	footModel = args[8];

	mtDocument = args[9];

	stamp = args[10];

	username = args[11];

	var TANGER_OCX_OBJ = document.getElementById("TANGER_OCX");

	var tb;

	var buttondiv = document.createElement("div");
	buttondiv.id = "toolbar";
	document.body.insertBefore(buttondiv, document.body.childNodes[0]);
	tb = new Ext.Toolbar();

	if (handleType == '1') {
		/*
		 * var buttondiv = document.createElement("div"); buttondiv.id =
		 * "toolbar"; document.body.insertBefore(buttondiv,
		 * document.body.childNodes[0]);
		 * 
		 * tb = new Ext.Toolbar();
		 */

		var saveAction = new Ext.Action({
					text : '<span style="font-size: 14px" title="保存正文内容">提交保存</font>',
					handler : function() {
						// 初始化控件参数
						var paraObj = new Object();
						paraObj.PARA = TANGER_OCX_FormPara();// 存储当前页面的所有输入域的数值
						paraObj.FFN = columnName;// 存储正文输入域的名称
						// TANGER_OCX_FormPara(paraObj);
						if (!paraObj.FFN) {
							alert("参数错误：控件的第二个参数没有指定。");
							return false;
						}

						// 保存正文
						var retStr = TANGER_OCX_OBJ.SaveToURL(context
										+ '/system/flow.do?method=savedoc',
								paraObj.FFN, paraObj.PARA, 'new document.doc');

						var o = Ext.util.JSON.decode(retStr);

						if (o.success) {
							docid = o.id;
							alert('正文保存成功！');
						} else {

						}
					},
					iconCls : 'save'
				});

		tb.add(saveAction);

		// 保存退出按钮
		var saveActionClose = new Ext.Action({
			text : '<span style="font-size: 14px" title="保存正文内容并关闭模态窗口">保存退出</font>',
			handler : function() {
				// 初始化控件参数
				var paraObj = new Object();
				paraObj.PARA = TANGER_OCX_FormPara();// 存储当前页面的所有输入域的数值
				paraObj.FFN = columnName;// 存储正文输入域的名称
				// TANGER_OCX_FormPara(paraObj);
				if (!paraObj.FFN) {
					alert("参数错误：控件的第二个参数没有指定。");
					return false;
				}

				// 保存正文
				var retStr = TANGER_OCX_OBJ.SaveToURL(context
								+ '/system/flow.do?method=savedoc',
						paraObj.FFN, paraObj.PARA, 'new document.doc');

				var o = Ext.util.JSON.decode(retStr);

				if (o.success) {
					docid = o.id;
					alert('正文保存成功！');

				} else {

				}
				window.close();
			},
			iconCls : 'send'
		});

		tb.add(saveActionClose);

	}

	if (handleType == '1' && taohong) {
		var thAction = new Ext.Action({
					text : '<span style="font-size: 14px" title="正文套红">正文套红</font>',
					handler : function() {

						// TANGER_OCX_OBJ = document.all.item("TANGER_OCX");
						var sel = TANGER_OCX_OBJ.ActiveDocument.Application.Selection;
						if (TANGER_OCX_OBJ.ActiveDocument.Bookmarks
								.Exists('wh')) {
							alert('正文已套红！');
						} else {

							// 文件头部插入文件
							TANGER_OCX_SetReviewMode(TANGER_OCX_OBJ, false);
							try {
								sel.HomeKey(6);
								TANGER_OCX_OBJ.AddTemplateFromURL(headerModel);
							} catch (err) {
							};
							// 文件尾部插入文件
							try {
								sel.EndKey(6);
								TANGER_OCX_OBJ.AddTemplateFromURL(footModel);
							} catch (err) {
							};
							sel.TypeBackspace();
							TANGER_OCX_SetReviewMode(TANGER_OCX_OBJ, true);

						}
						init_word(mtDocument, TANGER_OCX_OBJ);
					},
					iconCls : 'red'
				});

		tb.add(thAction);
	}

	if (mtDocument.getElementById('flowAction').value.indexOf('view') == -1
			&& mtDocument.getElementById('flowAction').value.indexOf('look') == -1) {
		var hjAction = new Ext.Action({
					text : '<span style="font-size: 14px" title="显示痕迹">显示痕迹</font>',
					handler : function() {
						if (TANGER_OCX_OBJ.ActiveDocument.ProtectionType == -1) {
							try {
								TANGER_OCX_OBJ.ActiveDocument.ShowRevisions = true;
							} catch (err) {
							}

						} else {
							alert("文档已保护，无法使用此功能");
						}

					},
					iconCls : 'xshj'
				});

		tb.add(hjAction);

		var ycAction = new Ext.Action({
					text : '<span style="font-size: 14px" title="隐藏痕迹">隐藏痕迹</font>',
					handler : function() {
						if (TANGER_OCX_OBJ.ActiveDocument.ProtectionType == -1) {
							try {
								TANGER_OCX_OBJ.ActiveDocument.ShowRevisions = false;
							} catch (err) {
							}

						} else {
							alert("文档已保护，无法使用此功能");
						}

					},
					iconCls : 'ychj'
				});

		tb.add(ycAction);
	}

	if (tb) {
		tb.render('toolbar');
	}

	if (docid == '0') {
		TANGER_OCX_OBJ.OpenFromURL(doctemp);
	} else if (handleType == '0') {
		// TANGER_OCX_SetReadOnly(true);
		TANGER_OCX_OBJ.OpenFromURL(context + '/system/annex.do?method=load&id='
				+ docid);
		TANGER_OCX_SetReadOnly(true);
	} else if (handleType == '1') {
		TANGER_OCX_OBJ.OpenFromURL(context + '/system/annex.do?method=load&id='
				+ docid);
	}

	init_word(mtDocument, TANGER_OCX_OBJ);
}

function close_word() {
	window.returnValue = docid;
}

/**
 * 初始化保存正文时需要传入servlet的参数
 * 
 * @param {Object}
 *            paraObj
 */
function TANGER_OCX_FormPara(paraObj) {
	var str = 'columnName=' + columnName + '&';
	str += 'tableName=' + tableName + '&';
	str += 'docid=' + docid + '&';
	str += 'sequenceA=' + sequenceA;

	return str;
}

/**
 * 控件只读
 * 
 * @param {}
 *            boolvalue
 */
function TANGER_OCX_SetReadOnly(boolvalue) {
	// debugger;
	var i;
	try {
		if (boolvalue)
			TANGER_OCX_OBJ.IsShowToolMenu = false;
		with (TANGER_OCX_OBJ.ActiveDocument) {
			if (TANGER_OCX_OBJ.DocType == 1) // word
			{
				if ((ProtectionType != -1) && !boolvalue) {
					Unprotect();
				}
				if ((ProtectionType == -1) && boolvalue) {
					Protect(2, true, "");
				}
			} else if (TANGER_OCX_OBJ.DocType == 2)// excel
			{
				for (i = 1; i <= Application.Sheets.Count; i++) {
					if (boolvalue) {
						Application.Sheets(i).Protect("", true, true, true);
					} else {
						Application.Sheets(i).Unprotect("");
					}
				}
				if (boolvalue) {
					Application.ActiveWorkbook.Protect("", true);
				} else {
					Application.ActiveWorkbook.Unprotect("");
				}
			}
		}
	} catch (err) {
		// alert("\u9519\u8bef\uff1a" + err.number + ":" + err.description);
	} finally {
	}
}

/**
 * 初始化word
 * 
 * @param obj
 *            公文表单document
 * @param ntkoObj
 *            ntko activeX object
 */
function init_word(obj, ntkoObj) {

	var i, j, k;
	var wh_name = "";
	var elementArr = new Array("INPUT", "SELECT", "TEXTAREA");
	var pdGz = judge_gz(ntkoObj);
	if (!pdGz) {
		// **************对所有的书签先清稿***********************
		TANGER_OCX_SetReviewMode(ntkoObj, false);
		for (j = 0; j < elementArr.length; j++) {
			var tagObj = obj.getElementsByTagName(elementArr[j]);

			for (i = 0; i < tagObj.length; i++) {

				CopyValueToBookMark(tagObj[i].name, tagObj[i].name, obj,
						ntkoObj);
			}
		}

		for (k = 0; k < elementArr.length; k++) {
			var tagObj = obj.getElementsByTagName(elementArr[k]);

			for (i = 0; i < tagObj.length; i++) {

				if (tagObj[i].special == "number") {
					wh_name = tagObj[i].name;
					break;
				}
			}
		}
		tsFiled_word(obj, wh_name, ntkoObj);
		getLast_TableBottom(ntkoObj);
		TANGER_OCX_SetWordname(ntkoObj);
		TANGER_OCX_SetReviewMode(ntkoObj, true);
		TANGER_OCX_ShowRevisions(ntkoObj, false);
		if (stamp) {
			// 如果是盖章环节先清稿再保存
			ntkoObj.ActiveDocument.AcceptAllRevisions();
			ntkoObj.ActiveDocument.TrackRevisions = false;
		}
	}
	display_gz(obj, ntkoObj);

}

/**
 * 将表单页面上指定输入域的value拷贝到正文中对应的标签中
 * 
 * @param {Object}
 *            inputname 表单页面上指定输入域的名称
 * @param {Object}
 *            BookMarkName 正文中对应的标签名称
 */
function CopyValueToBookMark(inputname, BookMarkName, obj, ntkoObj) {
	try {
		var inputValue = "";
		var j, elObj, optionItem;
		var elObj = obj.getElementById(inputname);
		if (!elObj) {
			return;
		}
		// 根据当前对象类型的不同，获取对象的value
		switch (elObj.type) {
			case "select-one" :
				inputValue = elObj.options[elObj.selectedIndex].text;
				break;
			case "select-multiple" :
				var isFirst = true;
				for (j = 0; j < elObj.options.length; j++) {
					optionItem = elObj.options[j];
					if (optionItem.selected) {
						if (isFirst) {
							inputValue = optionItem.text;
							isFirst = false;
						} else {
							inputValue += "  " + optionItem.text;
						}
					}
				}

				break;
			case "checkbox" :
				var eles = obj.getElementsByName(inputname);
				if (eles != null) {
					for (var k = 0; k < eles.length; k++) {
						if (eles[k].checked == true) {
							// alert("eles[k].value======"+eles[k].value);
							inputValue = eles[k].value;
							break;
						}
					}
				}

				break;
			default : // text,Areatext,selecte-one,password,submit,etc.
				inputValue = elObj.value;
				break;
		}

		var mybt = "";
		if (obj.getElementById("fwbt") != null) {
			mybt = obj.getElementById("fwbt").value;
		}

		if (inputname == "keyBT" && inputValue == mybt) {
		} else {

			// TANGER_OCX_OBJ = document.all.item("TANGER_OCX");
			// 将对象的value拷贝到对应的标签对象中
			var bkmkObj = ntkoObj.ActiveDocument.BookMarks(BookMarkName);
			// var tacheid = opener.document.getElementById("tacheid").value;

			if (!bkmkObj) {
			}
			var saverange = bkmkObj.Range
			saverange.Text = inputValue;
			if (inputname == "keyZTC") {
				saverange.Font.NameFarEast = "方正小标宋简体";
				saverange.Font.NameAscii = "方正小标宋简体";
			}

			ntkoObj.ActiveDocument.Bookmarks.Add(BookMarkName, saverange);

		}

	} catch (err) {

	}
}
/**
 * 特殊域往正文带值操作
 * 
 * @param {}
 *            obj
 * @param {}
 *            wh_name
 */
function tsFiled_word(obj, wh_name, ntkoObj) {

	// TANGER_OCX_OBJ = document.all.item("TANGER_OCX");
	if (ntkoObj.ActiveDocument.Bookmarks.Exists("wh")) {
		var bkmkObj1 = ntkoObj.ActiveDocument.BookMarks("wh");
		var saverange1 = bkmkObj1.Range;
		saverange1.Text = obj.getElementById(wh_name).value;
		ntkoObj.ActiveDocument.Bookmarks.Add("wh", saverange1);
	}
}

/**
 * 显示签章按钮判断
 * 
 * @param {}
 *            obj
 */
function display_gz(obj, ntkoObj) {
	// TANGER_OCX_OBJ = document.all.item("TANGER_OCX");
	if (stamp) {
		try {
			ntkoObj.ActiveDocument.CommandBars("NTKO安全签名印章").Visible = true;
		} catch (err) {
		}
	} else {

		try {
			ntkoObj.ActiveDocument.CommandBars("NTKO安全签名印章").Visible = false;

		} catch (err) {
		}
	}

}

/**
 * 判断文档是否有盖章
 */
function judge_gz(ntkoObj) {
	var judgeGz = false;
	// TANGER_OCX_OBJ = document.all.item("TANGER_OCX");
	var myDoc = ntkoObj.ActiveDocument;
	var shapes = myDoc.shapes;
	for (i = 1; i <= shapes.Count; i++) {
		var curShape = shapes(i);
		if (12 == curShape.Type) {

			if ("NTKO.SecSignControl".toUpperCase() == curShape.OLEFormat.ClassType
					.toUpperCase()) {

				// **********
				judgeGz = true;
				break;

			}

		}

	}
	return judgeGz;
}

function getLast_TableBottom(ntkoObj) {
	if (stamp) {
		var mydoc = ntkoObj.ActiveDocument;
		var sel = mydoc.Application.Selection;
		var docshapes = mydoc.Shapes;
		var table_len = mydoc.Tables.Count;
		var last_table = mydoc.Tables(table_len);
		last_table.Range.Select();
		// *********************************************让版记自动沉底
		last_table.Rows.WrapAroundText = true;
		last_table.Rows.RelativeHorizontalPosition = 0;
		last_table.Rows.VerticalPosition = -999997;
		last_table.Rows.RelativeVerticalPosition = 0;
		last_table.Rows.AllowOverlap = true;
		sel.EndKey(5);
	}

}

function TANGER_OCX_SetWordname(ntkoObj) {
	if (ntkoObj.ActiveDocument.ProtectionType == -1) {

		ntkoObj.WebUserName = username;
	}

}

// 切换打开或者关闭修订模式
function TANGER_OCX_SetReviewMode(ntkoObj, boolvalue) {
	if (ntkoObj.ActiveDocument.ProtectionType == -1) {

		ntkoObj.ActiveDocument.TrackRevisions = boolvalue;
	}

}

// 显示/不显示修订文字
function TANGER_OCX_ShowRevisions(ntkoObj, boolvalue) {
	if (ntkoObj.ActiveDocument.ProtectionType == -1) {

		ntkoObj.ActiveDocument.ShowRevisions = boolvalue;
	}

}
